from collections.abc import Generator
import tempfile
from typing import Any
import subprocess
import os
import uuid
import json

# 修复导入错误，使用相对导入
from core.mcp import mcp

mcp.get_tools

def convert_markdown_to_markmap(markdown_text):
    """
    Convert Markdown text to Markmap HTML format.
    
    :param markdown_text: Input Markdown text
    :return: Generated HTML content
    """
    # Create temporary file to save Markdown content
    with tempfile.NamedTemporaryFile(mode='w+', suffix=".md", delete=False) as md_file:
        md_file.write(markdown_text)
        md_path = md_file.name
    
    try:
        # Create temporary HTML file for output
        with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as html_file:
            html_path = html_file.name
        
        # Use markmap to generate HTML file
        subprocess.run(
            ['markmap', '--no-open', f'--output={html_path}', md_path],
            check=True
        )

        # Read the HTML file
        with open(html_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return content
    
    finally:
        # Clean up temporary files
        os.remove(md_path)
        os.remove(html_path)

        
# @mcp.tool(description="markdown生成思维导图")
def mindmap_tool(markdown_text: str):
    # Get markdown text from parameters
    
    # If we still don't have text, return an error
    if not markdown_text:
        return {
            "success": False,
            "error": "No markdown text provided. Please provide 'markdown_text' parameter."
        }
    
    try:
        # Convert markdown to mindmap HTML
        html_output = convert_markdown_to_markmap(markdown_text)
        
        # Generate a unique filename
        output_filename = f"mindmap_{str(uuid.uuid4()).upper()}.html"
        
        # Return as a successful result with the HTML content
        return {
            "success": True,
            "content": f"Mindmap generated successfully. File: {output_filename}",
            "files": [{
                "filename": output_filename,
                "content": html_output
            }]
        }
    except subprocess.CalledProcessError as e:
        return {
            "success": False,
            "error": f"Failed to convert markdown to mindmap: {str(e)}",
        }
    except Exception as e:
        return {
            "success": False,
            "error": f"An unexpected error occurred: {str(e)}"
        }
    

if __name__ == "__main__":
    # Example usage
    markdown_text = """
    # Example Markdown

    This is an example of markdown text.

    - List item 1
    - List item 2
    """
    
    result = mindmap_tool(markdown_text)
    print(result)